package com.atguigu.day04;

import com.atguigu.utils.ClickEvent;
import com.atguigu.utils.ClickSource;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickSource())
                .keyBy(r -> r.username)
                .process(new KeyedProcessFunction<String, ClickEvent, String>() {
                    // key: url
                    // value: url的访问次数
                    private MapState<String, Integer> urlCount;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        urlCount = getRuntimeContext().getMapState(
                                new MapStateDescriptor<String, Integer>(
                                        "url-count",
                                        Types.STRING, // KEY的泛型
                                        Types.INT     // VALUE的泛型
                                )
                        );
                    }

                    @Override
                    public void processElement(ClickEvent in, Context ctx, Collector<String> out) throws Exception {
                        if (!urlCount.contains(in.url)) {
                            urlCount.put(in.url, 1);
                        } else {
                            urlCount.put(in.url, urlCount.get(in.url) + 1);
                        }

                        // 打印输入数据的key的字典状态变量
                        String username = ctx.getCurrentKey();
                        String result = "用户" + username + "的字典状态变量是：{\n";
                        for (String url : urlCount.keys()) {
                            result += "  '" + url + "' => " + urlCount.get(url) + ",\n";
                        }
                        result += "}\n";
                        out.collect(result);
                    }
                })
                .print();

        env.execute();
    }
}
